package com.elong.businesstravel.modules.home.ticket;

import java.io.File;
import java.util.Date;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.android.support.jhf.utils.DateUtils;
import com.android.support.jhf.utils.FileUtils;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.Constant;
import com.elong.businesstravel.base.basefragment.BaseFragment;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.entitys.City;
import com.elong.businesstravel.entitys.Poi;
import com.elong.businesstravel.entitys.TicketSearchCondition;
import com.elong.businesstravel.entitys.TrainStation;
import com.elong.businesstravel.modules.home.hotel.search.HotelCitySelectActivity;
import com.elong.businesstravel.modules.home.ticket.search.StationListActivity;
import com.elong.businesstravel.modules.home.ticket.search.TrainStartingDateActivity;
import com.elong.businesstravel.modules.home.ticket.ticketshow.TicketListActivity;
import com.elong.businesstravel.protocol.baseresponse.IHttpResponse;
import com.elong.businesstravel.protocol.ticket.GetStationListRequest;
import com.elong.businesstravel.protocol.ticket.GetStationListResponse;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

/**
 * 火车票
 * 
 * @author lenovo
 * 
 */
public class TrainTicketFragment extends BaseFragment {

	private TextView mStartCityTextView;
	private TextView mEndCityTextView;
	private TextView mStartDateTextView;

	private CheckBox mCrhCheckBox;
	private CheckBox mHaveTrainCheckBox;

	private TrainStation mSaveStartTrainStation;
	private TrainStation mSaveEndTrainStation;
	private Date mSaveStartDate;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_train_ticket, null);
		setViewData(view);
		return view;
	}

	@Override
	protected void setViewData(View view) {

		mCrhCheckBox = (CheckBox) view.findViewById(R.id.crhCheckBox);
		mHaveTrainCheckBox = (CheckBox) view
				.findViewById(R.id.haveTrainCheckBox);

		mStartCityTextView = (TextView) view
				.findViewById(R.id.startCityTextView);
		setStartStation();

		mEndCityTextView = (TextView) view.findViewById(R.id.endCityTextView);
		setEndStation();

		mStartDateTextView = (TextView) view
				.findViewById(R.id.startDateTextView);
		setStartingDate();

		setListener(view);
	}

	@Override
	protected void setListener(View view) {

		Button hotelSearchButton = (Button) view
				.findViewById(R.id.hotelSearchButton);
		hotelSearchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				TicketSearchCondition ticketSearchCondition = new TicketSearchCondition();
				ticketSearchCondition.startStation = SaveUserOperate
						.getStartTrainStation(mParentContext).toString();
				ticketSearchCondition.endStation = SaveUserOperate
						.getEndTrainStation(mParentContext).toString();
				ticketSearchCondition.startDate = DateUtils.dateFormat(
						SaveUserOperate.getTrainStartingDate(mParentContext)
								.getTime(), "yyyyMMdd");
				if (mCrhCheckBox.isChecked()) {
					// 只看高铁动车
					ticketSearchCondition.trainType = "1,2";
				} else {
					ticketSearchCondition.trainType = "0";
				}
				if (mHaveTrainCheckBox.isChecked()) {
					ticketSearchCondition.hasYp = "1";
				} else {
					ticketSearchCondition.hasYp = "0";
				}

				Intent intent = new Intent(mParentContext,
						TicketListActivity.class);
				intent.putExtra("ticketsearchcondition", ticketSearchCondition);
				startActivity(intent);
			}
		});

		ViewGroup startCityLayout = (ViewGroup) view
				.findViewById(R.id.startCityLayout);
		startCityLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				goStationListActivity(0);
			}
		});

		ViewGroup endCityLayout = (ViewGroup) view
				.findViewById(R.id.endCityLayout);
		endCityLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				goStationListActivity(1);
			}
		});

		ViewGroup startDateLayout = (ViewGroup) view
				.findViewById(R.id.startDateLayout);
		startDateLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mParentContext,
						TrainStartingDateActivity.class);
				mFragment.startActivityForResult(intent, 2);
				mFragment.getActivity().overridePendingTransition(
						R.anim.activity_bottom_top_enter_anim_translate,
						R.anim.activity_alpha_fixed);
			}
		});

		ViewGroup switchLayout = (ViewGroup) view
				.findViewById(R.id.switchLayout);
		switchLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				switchStartEndStation();
			}
		});
	}

	/**
	 * 切换始发和终点站
	 */
	private void switchStartEndStation() {

		TrainStation tempStartTrainStation = (TrainStation) mStartCityTextView
				.getTag();
		TrainStation tempEndTrainStation = (TrainStation) mEndCityTextView
				.getTag();

		SaveUserOperate.setStartTrainStation(mParentContext,
				tempEndTrainStation);
		SaveUserOperate.setEndTrainStation(mParentContext,
				tempStartTrainStation);

		setStartStation();
		setEndStation();

	}

	/**
	 * 设置始发站
	 */
	private void setStartStation() {
		mSaveStartTrainStation = SaveUserOperate
				.getStartTrainStation(mParentContext);
		if (null != mSaveStartTrainStation) {
			mStartCityTextView.setText(mSaveStartTrainStation.toString());
			mStartCityTextView.setTag(mSaveStartTrainStation);
		} else {
			if (null != mApplication.mTrainStations) {
				mStartCityTextView.setText(mApplication.mTrainStations.get(0)
						.toString());
				mStartCityTextView.setTag(mApplication.mTrainStations);
				SaveUserOperate.setStartTrainStation(mParentContext,
						mApplication.mTrainStations.get(0));
			} else {
				mStartCityTextView.setText("北京");
				TrainStation trainStation = new TrainStation();
				trainStation.setStatus("1");
				trainStation.setStationCode("BJP");
				trainStation.setStationName("北京");
				trainStation.setStationPY("beijing");
				trainStation.setStationPYS("bj");
				mStartCityTextView.setTag(trainStation);
				SaveUserOperate.setStartTrainStation(mParentContext,
						trainStation);
			}
		}
	}

	/**
	 * 设置终点站
	 */
	private void setEndStation() {
		mSaveEndTrainStation = SaveUserOperate
				.getEndTrainStation(mParentContext);
		if (null != mSaveEndTrainStation) {
			mEndCityTextView.setText(mSaveEndTrainStation.toString());
			mEndCityTextView.setTag(mSaveEndTrainStation);
		} else {
			if (null != mApplication.mTrainStations) {
				mEndCityTextView.setText(mApplication.mTrainStations.get(0)
						.toString());
				mEndCityTextView.setTag(mApplication.mTrainStations);
				SaveUserOperate.setStartTrainStation(mParentContext,
						mApplication.mTrainStations.get(0));
			} else {
				mEndCityTextView.setText("北京");
				TrainStation trainStation = new TrainStation();
				trainStation.setStatus("1");
				trainStation.setStationCode("BJP");
				trainStation.setStationName("北京");
				trainStation.setStationPY("beijing");
				trainStation.setStationPYS("bj");
				mEndCityTextView.setTag(trainStation);
				SaveUserOperate.setStartTrainStation(mParentContext,
						trainStation);
			}
		}
	}

	/**
	 * 设置出发时间
	 */
	private void setStartingDate() {
		mSaveStartDate = SaveUserOperate.getTrainStartingDate(mParentContext);

		if (null != mSaveStartDate) {
			mStartDateTextView.setText(DateUtils.dateFormat(
					mSaveStartDate.getTime(), "yyyy/MM/dd"));
			mStartDateTextView.setTag(mSaveStartDate);
		} else {
			Date date = new Date();
			date.setTime(System.currentTimeMillis());
			SaveUserOperate.setTrainStartingDate(mParentContext, date);
			mStartDateTextView.setTag(date);
			mStartDateTextView.setText(DateUtils.dateFormat(
					System.currentTimeMillis(), "yyyy/MM/dd"));
		}

	}

	/**
	 * 跳转城市
	 */
	private void goStationListActivity(final int requestCode) {
		if (null != mApplication.mTrainStations) {
			Intent intent = new Intent(mParentContext,
					StationListActivity.class);
			if (0 == requestCode) {
				intent.putExtra("title", "始发车站");
			} else if (1 == requestCode) {
				intent.putExtra("title", "终点车站");
			}
			intent.putExtra("flag", requestCode);
			mFragment.startActivityForResult(intent, requestCode);
			mFragment.getActivity().overridePendingTransition(
					R.anim.activity_bottom_top_enter_anim_translate,
					R.anim.activity_alpha_fixed);
		} else {
			getTrainList(new IHttpResponse() {

				@Override
				public void onResponse(
						ResponseHandlerInterface responseHandlerInterface) {
					HandlerPostUI.getHandlerPostUI(new Runnable() {

						@Override
						public void run() {
							Intent intent = new Intent(mParentContext,
									StationListActivity.class);
							if (0 == requestCode) {
								intent.putExtra("title", "始发车站");
							} else if (1 == requestCode) {
								intent.putExtra("title", "终点车站");
							}
							intent.putExtra("flag", requestCode);
							mFragment.startActivityForResult(intent,
									requestCode);
							mFragment
									.getActivity()
									.overridePendingTransition(
											R.anim.activity_bottom_top_enter_anim_translate,
											R.anim.activity_alpha_fixed);

						}
					});
				}
			});
		}
	}

	/**
	 * 获取车站列表
	 * 
	 * @param iHttpResponse
	 */
	private void getTrainList(final IHttpResponse iHttpResponse) {

		final Md5FileNameGenerator md5FileNameGenerator = new Md5FileNameGenerator();
		final GetStationListRequest getStationListRequest = new GetStationListRequest(
				mParentContext);
		final String cacheKeyString = mParentContext.getCacheDir()
				+ "/"
				+ md5FileNameGenerator.generate(getStationListRequest
						.getCacheKey());

		NetworkClient.getNetworkClient().PostRequest(getStationListRequest,
				new GetStationListResponse() {
					@Override
					public void onResponse(
							final ResponseHandlerInterface responseHandlerInterface) {
						mApplication.mTrainStations = ((GetStationListResponse) responseHandlerInterface).trainStations;
						String responseString = ((GetStationListResponse) responseHandlerInterface).responseString;
						FileUtils.saveFile(responseString, new File(
								cacheKeyString));
						if (null != iHttpResponse) {
							iHttpResponse.onResponse(responseHandlerInterface);
						}
					}
				});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0: {
			// 始发车站
			switch (resultCode) {
			case Activity.RESULT_OK: {

				TrainStation trainStation = (TrainStation) data
						.getSerializableExtra("trainStation");
				mStartCityTextView.setText(trainStation.toString());

				break;

			}
			case Activity.RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 1: {
			// 终点站
			switch (resultCode) {
			case Activity.RESULT_OK: {

				TrainStation trainStation = (TrainStation) data
						.getSerializableExtra("trainStation");
				mEndCityTextView.setText(trainStation.toString());

				break;

			}
			case Activity.RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;

		}
		case 2: {
			// 出发日期返回
			switch (resultCode) {
			case Activity.RESULT_OK: {

				String date = data.getStringExtra("date");
				mStartDateTextView.setText(date);

				break;

			}
			case Activity.RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

}
